# -*- coding: utf-8 -*-

from pyquery import PyQuery
from crccbuy.items import crccbuySpu
from zc_core.model.items import Catalog
from zc_core.model.items import ItemData
from zc_core.util.http_util import *


# 解析catalog列表
def parse_catalog(response):
    cats = list()
    jpy = PyQuery(response.text)
    for jpy1 in jpy('.cates li').items():
        # TODO 一级分类
        cat1_id = re.search('\d+', jpy1('h3 a').attr('href')).group()
        cat1_name = jpy1('h3').text()
        cat11 = _build_catalog(cat1_id, cat1_name, '', 1)
        cats.append(cat11)
        for jpy2 in jpy1('dl').items():
            # TODO 二级分类
            cat2_id = re.search('\d+', jpy2('dt a').attr('href')).group()
            cat2_name = jpy2('dt a').text()
            cat22 = _build_catalog(cat2_id, cat2_name, cat1_id, 2)
            cats.append(cat22)
            for jpy3 in jpy2('dd a').items():
                # TODO 三级分类
                cat3_id = re.search('\d+', jpy3('a').attr('href')).group()
                cat3_name = jpy3('a').text()
                cat33 = _build_catalog(cat3_id, cat3_name, cat2_id, 3)
                cats.append(cat33)
    return cats


def _build_catalog(cat_id, cat_name, parent_id, level):
    cat = Catalog()
    cat['catalogId'] = cat_id
    cat['catalogName'] = cat_name
    cat['parentId'] = parent_id
    cat['level'] = level
    if level == 3:
        cat['leafFlag'] = 1
    else:
        cat['leafFlag'] = 0
    cat['linkable'] = 0

    return cat


# 维度：三级分页，解析spu列表页数
def parse_total_page(response):
    jpy = PyQuery(response.text)
    page_list = [i.text() for i in jpy('.page_link').items()]
    if page_list.__len__() != 0:
        page = page_list[-1]
    else:
        page = [i.text() for i in jpy('.page_hover').items()][-1]
    return int(page)


# 解析sku列表
def parse_spu(response):
    meta = response.meta
    batch_no = meta.get('batchNo')
    jpy = PyQuery(response.text)
    spus = list()
    for jpy1 in jpy('.item').items():
        spu = crccbuySpu()
        spu['spuId'] = re.search('\d+', jpy1('dt a').attr('href')).group()
        spu['batchNo'] = batch_no
        spus.append(spu)
    return spus


# 解析ItemData
def parse_item_data(response):
    meta = response.meta
    batch_no = meta.get('batchNo')
    spu_id = meta.get('spuId')
    jpy = PyQuery(response.text)
    result = ItemData()
    # 批次编号
    result['batchNo'] = batch_no
    # 平台商品ID（用于业务系统）
    # specs.push(new spec(2141, 'BV1.5', '黑色', 79.00,0, 997,false,0));
    # print(response.url, spu_id, re.findall('specs.push\(new spec\((.*?)\)\);', response.text, re.S))
    data_list = re.findall('specs.push\(new spec\((.*?)\)\);', response.text, re.S)
    for data in data_list:
        data = data.replace('"', '').split(',')
        if data[0].strip().__len__() != 0:

            result['skuId'] = data[0]
            result['spuId'] = spu_id
            # 平台商品名称（标题） #TODO
            sku_name = jpy('.ware_title').text()
            result['skuName'] = sku_name
            # sale_price = [i.text() for i in jpy('.ware_text .rate span').items()][1].replace('￥', '').replace(',', '')
            sale_price = [i.text() for i in jpy('.ware_text span').items() if i.attr('ectype') == 'goods_price'][
                0].replace('￥', '').replace(',', '')
            if sale_price != "面议" and data[3].strip() not in ['0.00','0.0','0']:
                sale_price = float(sale_price)
                # origin_price = float(
                #     [i.text() for i in jpy('.ware_text .rate span').items()][3].replace('￥', '').replace(',', ''))
                origin_price = float([i.text() for i in jpy('.ware_text span').items() if
                                      i.attr('style') == 'text-decoration:line-through;'][0].replace('￥', '').replace(
                    ',', ''))
                result['originPrice'] = sale_price if origin_price == 0.0 or origin_price == 0.00 else origin_price
                # print("打印",data[3].strip() not in ['0.00','0.0','0'],data[3],type(data[3]),spu_id)
                result['salePrice'] = float(data[3])
                # stock = re.search('\d+', jpy('.handle').text())
                # if not stock:
                #     stock = re.search('\d+', [i('.floatLeft').text() for i in jpy('div:contains("剩余库存")').items()][-1])
                #     if stock:
                #         stock = stock.group()
                # else:
                #     stock = stock.group()
                # if stock:
                #     result['stock'] = stock
                result['stock'] = data[5].strip()
                # 供应商名字
                supplier_name = jpy('.user h2').text()
                if supplier_name.strip().__len__() == 0:
                    supplier_name = jpy('.store-tit').text()
                result['supplierName'] = supplier_name
                # 供应商ID
                supplier_id = jpy('.user .photo a').attr('href')
                if not supplier_id:
                    supplier_id = re.search('\d+', [i.attr('href') for i in jpy('.enter-store a').items()][0]).group()
                else:
                    supplier_id = result['supplierId'] = re.search('\d+', supplier_id).group()
                result['supplierId'] = supplier_id
                catalog1_id = re.search('\d+', [i.attr('href') for i in jpy('div .location a').items()][2]).group()
                result['catalog1Id'] = catalog1_id
                catalog1_name = [i.text() for i in jpy('div .location a').items()][2]
                result['catalog1Name'] = catalog1_name
                catalog2_id = re.search('\d+', [i.attr('href') for i in jpy('div .location a').items()][3]).group()
                result['catalog2Id'] = catalog2_id
                catalog2_name = [i.text() for i in jpy('div .location a').items()][3]
                result['catalog2Name'] = catalog2_name
                catalog3_id = re.search('\d+', [i.attr('href') for i in jpy('div .location a').items()][4]).group()
                result['catalog3Id'] = catalog3_id
                catalog3_name = [i.text() for i in jpy('div .location a').items()][4]
                result['catalog3Name'] = catalog3_name
                result['soldCount'] = int(re.search('售出 (\d+) 件', response.text).group(1))
                if data[1] == data[2]:
                    brandModel = data[1].replace("'", '').replace('"', '').strip()
                else:
                    brandModel = (data[1] + data[2]).replace("'", '').replace('"', '').strip()
                if brandModel.strip().__len__() != 0:
                    result['brandModel'] = brandModel
                yield result
